package com.yuandian.customer.perception.controller;

import com.yuandian.api.customer_perception.po.AreaAnalysisParams;
import com.yuandian.api.customer_perception.vo.*;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.data.resolver.ParamResolver;
import com.yuandian.customer.perception.service.IAreaAnalysisService;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.MathUtil;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 地市分析Controller
 *
 * @Author pmx
 * @Date 2021/8/17
 */
@Slf4j
@Api(value = "地市分析接口", tags = "地市分析接口")
@RestController
@RequestMapping("/area/analysis")
public class AreaAnalysisController {

    @Autowired
    private IAreaAnalysisService areaAnalysisService;


    /**
     * 区域概况
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-区域概况", notes = "地市分析-区域概况")
	@RequestMapping("/summary")
    public R<Object> summary(@RequestBody AreaAnalysisParams params) {
        AreaSummaryVo vo = new AreaSummaryVo();
        R<Object> result = areaAnalysisService.areaSystemHealth(params);
        if (result.getCode() != HttpStatus.SC_OK) {
            return result;
        }
        List<AreaSystemHealthVo> list = BeanUtils.cast(result.getData());
        if(list!=null && list.size()>0) {
            double threshold = 90.00D;
			String thresholdStr =  ParamResolver.getStr("sys.threshold.unhealth.system");
            if(thresholdStr!=null && !"".equals(thresholdStr)) {
                threshold = Double.parseDouble(thresholdStr);
            }
            vo.setSystemCount(list.size());
            int healthCount = 0;
            for(AreaSystemHealthVo health : list) {
                if(health.getHealthRate() > threshold) {
                    healthCount++;
                }
            }
            vo.setHealthCount(healthCount);
            vo.setUnHealthCount(vo.getSystemCount() - vo.getHealthCount());
        }
        return R.ok(vo);
    }

    /**
     * 区域系统健康度总览
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-区域系统健康度总览", notes = "地市分析-区域系统健康度总览")
	@RequestMapping("/systemHealth")
    public R<Object> systemHealth(@RequestBody AreaAnalysisParams params) {
        return areaAnalysisService.areaSystemHealth(params);
    }

    /**
     * 区域业务办理情况趋势图
     * 业务告警量,业务失败量,业务访问量,业务受理量-busi_sys_detail_stat_m-KhgzBusinessDetailStatTask-区域业务办理情况趋势图-延迟3分钟-/api-khgz/modules/area/analysis/trend
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-区域业务办理情况趋势图", notes = "地市分析-区域业务办理情况趋势图")
	@RequestMapping("/trend")
    public R<Object> trend(@RequestBody AreaAnalysisParams params) {
        return areaAnalysisService.areaTrend(params);
    }

    /**
     * 办事处总览列表
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处总览列表", notes = "地市分析-办事处总览列表")
	@RequestMapping("/businessHallView")
    public R<Object> businessHallView(@RequestBody AreaAnalysisParams params) {
        return areaAnalysisService.businessHallView(params);
    }

    /**
     * 办事处总览列表 - 下载
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处总览列表 - 下载", notes = "地市分析-办事处总览列表 - 下载")
	@RequestMapping("/businessHallView/excel")
    public void businessHallViewExcel(@RequestBody AreaAnalysisParams params, HttpServletResponse response) throws Exception {
        params.setPageNum(1);
        params.setPageSize(-1);

        R<Object> result = areaAnalysisService.businessHallView(params);
        PageDataInfo info = new PageDataInfo(0L, new ArrayList<BusinessHallViewVo>());
        if (result.getCode() == HttpStatus.SC_OK) {
            info = BeanUtils.cast(result.getData());
        }

        List<BusinessHallViewVo> data = new ArrayList<>();
        try {
            data = (List<BusinessHallViewVo>) info.getData();
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }
        for (BusinessHallViewVo datum : data) {
            datum.setSuccessRate(datum.getSuccessRate() + "%");
            datum.setHealthRate(datum.getHealthRate() + "%");
        }
        String title = params.getOfficeName() + "总览列表";

        String fileName = title + System.currentTimeMillis();

        //设置大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        titleParams.add(params.getAreaName());
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getQueryStartTime(),params.getQueryEndTime());

        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号",params.getOfficeName() + "ID",params.getOfficeName() + "名称", "操作员活跃数量", "系统活跃数量", "业务活跃数量", "访问量", "受理量", "告警访问量",
                "失败访问量", "成功率", "健康度");

        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });
        //回填序号并处理数据,分情况回填未知
        int index = 1;
        for (BusinessHallViewVo vo : data) {
            vo.setId(index++);
            if (vo.getBusinessHallId() == null || vo.getBusinessHallId().equals("")) {
                vo.setBusinessHallId("-");
            }
            if (vo.getBusinessHallName() == null || vo.getBusinessHallName().equals("")) {
                if (vo.getBusinessHallId() == "-") {
                    vo.setBusinessHallName("-");
                } else {
                    vo.setBusinessHallName("未知");
                }
            }
        }
        ExcelUtil.writeExcel(BusinessHallViewVo.class, "", "单位总览列表", data, headList, 20, response);
    }

    /**
     * 办事处-系统总览列表
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处-系统总览列表", notes = "地市分析-办事处-系统总览列表")
	@RequestMapping("/systemView")
    public R<Object> systemView(@RequestBody AreaAnalysisParams params) {
        return areaAnalysisService.systemView(params);
    }


    /**
     * 办事处-系统总览列表 - 下载
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处-系统总览列表 - 下载", notes = "地市分析-办事处-系统总览列表 - 下载")
	@RequestMapping("/systemView/excel")
    public void systemViewExcel(@RequestBody AreaAnalysisParams params, HttpServletResponse response) throws Exception {
        params.setPageNum(1);
        params.setPageSize(Integer.MAX_VALUE);

        R<Object> result = areaAnalysisService.systemView(params);
        PageDataInfo info = new PageDataInfo(0L, new ArrayList<SystemViewVo>());
        if (result.getCode() == HttpStatus.SC_OK) {
            info = BeanUtils.cast(result.getData());
        }

        List<SystemViewVo> data = new ArrayList<>();
        try {
            data =  (List<SystemViewVo>) info.getData();
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }
        for (SystemViewVo datum : data) {
            datum.setSuccessRate(datum.getSuccessRate() + "%");
            datum.setHealthRate(datum.getHealthRate() + "%");
        }

        String title = "系统总览列表";

        String fileName = title + System.currentTimeMillis();

        //设置大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        if (params.getAreaName() != null && params.getAreaName() != ""){
            titleParams.add(params.getAreaName());
        }
        if (params.getBusinessHallId() != null && params.getBusinessHallId() != ""){
            titleParams.add(params.getBusinessHallId());
        }
        if (params.getBusinessHallName() != null && params.getBusinessHallName() != ""){
            titleParams.add(params.getBusinessHallName());
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getQueryStartTime(),params.getQueryEndTime());

        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号","系统名称", "业务活跃数量", "访问量", "受理量",
                "告警访问量", "失败访问量", "平均响应时长", "成功率", "健康度");

        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });
        //回填序号
        int index = 1;
        for (SystemViewVo datum : data) {
            // 时间单位转化
            datum.setAvgServerResponseTimeStr(datum.getAvgServerResponseTime() == null ? "" :
                    YDateUtil.getMinSecond(MathUtil.getDouble(Double.parseDouble(datum.getAvgServerResponseTime().toString()) / 1000)));

            datum.setId(index++);
        }
        ExcelUtil.writeExcel(SystemViewVo.class, fileName, title, data, headList, 20, response);
    }

    /**
     * 办事处-系统-业务总览列表
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处-系统-业务总览列表", notes = "地市分析-办事处-系统-业务总览列表")
	@RequestMapping("/businessView")
    public R<Object> businessView(@RequestBody AreaAnalysisParams params) {
        return areaAnalysisService.businessView(params);
    }


    /**
     * 办事处-系统-业务总览列表 - 下载
     * @param params 请求参数
     * @return 通用结果集
     */
	@ApiOperation(value = "地市分析-办事处-系统-业务总览列表 - 下载", notes = "地市分析-办事处-系统-业务总览列表 - 下载")
	@RequestMapping("/businessView/excel")
    public void businessViewExcel(@RequestBody AreaAnalysisParams params, HttpServletResponse response) throws Exception {
        params.setPageNum(1);
        params.setPageSize(Integer.MAX_VALUE);

        R<Object> result = areaAnalysisService.businessView(params);
        PageDataInfo info = new PageDataInfo(0L, new ArrayList<BusinessViewVo>());
        if (result.getCode() == HttpStatus.SC_OK) {
            info = BeanUtils.cast(result.getData());
        }

        List<BusinessViewVo> data = new ArrayList<>();
        try {
            data = (List<BusinessViewVo>) info.getData();
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }
        for (BusinessViewVo datum : data) {
            datum.setSuccessRate(datum.getSuccessRate() + "%");
            datum.setHealthRate(datum.getHealthRate() + "%");
        }

        String title = "业务总览列表";
        String businessHallName = "";
        if (null != params.getBusinessHallName() && params.getBusinessHallName().trim().length() > 0) {
            businessHallName = params.getBusinessHallName();
        } else if (params.getBusinessHall() != null && params.getBusinessHall() != "" && params.getOfficeName() != null && params.getOfficeName() != ""){
            businessHallName = params.getBusinessHall() + params.getOfficeName();
        }


        String fileName = title + System.currentTimeMillis();

        //设置大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        if (params.getAreaName() != null && params.getAreaName() != ""){
            titleParams.add(params.getAreaName());
        }
        if (params.getBusinessHallId() != null && params.getBusinessHallId() != ""){
            titleParams.add(params.getBusinessHallId());
        }
        if (params.getBusinessHallName() != null && params.getBusinessHallName() != ""){
            titleParams.add(params.getBusinessHallName());
        }
        if (params.getSystemName() != null && params.getSystemName() != ""){
            titleParams.add(params.getSystemName());
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getQueryStartTime(),params.getQueryEndTime());
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号","业务名称", "访问量", "受理量", "告警访问量",
                 "失败访问量", "平均办理时长", "平均响应时长", "成功率", "健康度");

        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });
        //回填序号
        int index = 1;
        for (BusinessViewVo datum : data) {
            // 时间单位转化
            datum.setAvgVisitTimeStr(datum.getAvgVisitTime() == null ? "" :
                    YDateUtil.getMinSecond(MathUtil.getDouble(Double.parseDouble(datum.getAvgVisitTime().toString()) / 1000)));
            datum.setAvgServerResponseTimeStr(datum.getAvgServerResponseTime() == null ? "" :
					YDateUtil.getMinSecond(MathUtil.getDouble(Double.parseDouble(datum.getAvgServerResponseTime().toString()) / 1000)));

            datum.setId(index++);
        }
        ExcelUtil.writeExcel(BusinessViewVo.class, fileName, title, data, headList, 20, response);
    }
}
